package org.hw.controller;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.hw.dto.PublishRequest;
import org.hw.dto.SubscribeRequest;
import org.hw.entity.Monitordata;
import org.hw.service.MonitordataService;
import org.hw.util.MqttUtil;
import org.hw.util.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/mqtt")
public class MqttController {

    @Autowired
    private MonitordataService monitordataService;

    /**
     * 订阅多个主题
     * @param request 订阅请求对象，包含主题数组和服务质量
     * @return 订阅结果响应实体
     */
    @PostMapping("/subscribe")
    @Transactional
    public ResultData<?> subscribe(@RequestBody SubscribeRequest request) {
        try {
            String[] topics = request.getTopics();
            int qos = request.getQos();
            System.out.println("订阅主题: " + String.join(", ", topics));
            System.out.println("订阅服务质量: " + qos);
            MqttUtil.subscribeMultiple(topics, qos, new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.err.println("连接丢失，原因: " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    String payload = new String(message.getPayload());
                    System.out.printf("Controller收到来自主题 [%s] 的消息: %s%n", topic, payload);


                    // 处理testtopic/send主题的消息
                    if ("testtopic/send".equals(topic)) {
                        try {
                            // 使用Monitordata自带的JSONparse方法解析消息
                            Monitordata monitorData = Monitordata.JSONparse(payload);
                            if (monitorData != null) {
                                // 保存到数据库
                                boolean saved = monitordataService.saveMonitorData(monitorData);
//                                        saveMonitorData(monitorData);
                                if (saved) {
                                    System.out.println("数据成功保存到数据库");
                                } else {
                                    System.out.println("数据保存失败");
                                }
                            }
                        } catch (Exception e) {
                            System.err.println("处理消息时出错: " + e.getMessage());
                        }
                    }
                }

                @Override
                public void deliveryComplete(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken token) {
                    // 消息传递完成回调，可按需处理
                }
            });
            return ResultData.success("Successfully subscribed to topics: " + String.join(", ", topics));
        } catch (Exception e) {
            System.out.println("订阅失败: " + e.getMessage());
            return ResultData.fail("Failed to subscribe to topics: " + e.getMessage());
        }
    }
    /**
     * 发布消息到指定主题
     * @param request 发布请求对象，包含主题、消息内容和服务质量
     * @return 发布结果响应实体
     */
    @PostMapping("/publish")
    @Transactional
    public ResultData<String> publishMessage(@RequestBody PublishRequest request) {
        try {
            String topic = request.getTopic();
            String message = request.getMessage();
            int qos = request.getQos();
            MqttUtil.publish(topic, message, qos);
            return ResultData.success("消息发布成功到主题: " + topic);
        } catch (Exception e) {
            return ResultData.fail("消息发布失败: " + e.getMessage());
        }
    }
}